package com.tsfyun.common.base.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.tsfyun.common.base.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;

import java.util.*;

/**
 * @Description: 签名工具类
 * @CreateDate: Created in 2021/3/16 14:13
 */
@Slf4j
public class SignUtil {

    static final String SIGN = "sign";

    /**
     * RAS签名
     * @param requestMap
     * @param privateKey
     * @return
     * @throws Exception
     */
    public static String rsaSign(Map<String, Object> requestMap,String privateKey) {
       String signStr  = sort(requestMap);
        try {
            return RSAUtils.signByPrivateKey(signStr.getBytes(), privateKey);
        } catch (Exception e) {
            log.error("RAS私钥加签异常",e);
            throw new ServiceException("系统加签失败");
        }
    }

    /**
     * 字典码排序
     * @param requestMap
     * @return
     */
    public static String sort(Map<String, Object> requestMap){
        //Key值排序
        Collection<String> keySet = requestMap.keySet();
        List<String> list = new ArrayList<>(keySet);
        Collections.sort(list);
        //组装签名字符串
        StringBuffer signStr = new StringBuffer();
        for(int i = 0,size = list.size(); i < size; i++){
            String key = list.get(i);
            if(Objects.equals(key,SIGN)) {
                continue;
            }
            Object value = requestMap.get(key);
            //参数值为空，则不参与签名，参数不去前后空格
            if (value != null && value.toString().trim().length() > 0) {
                if(value instanceof JSONObject || value instanceof JSONArray) {
                    value = ((JSON) value).toJSONString(value,SerializerFeature.WriteMapNullValue);
                    signStr.append(key).append("=").append(value).append("&");
                } else {
                    signStr.append(key).append("=").append(value).append("&");
                }
            }
        }
        //去掉最后一个&号
        signStr.deleteCharAt(signStr.length() - 1);
        return signStr.toString();
    }

}
